
package com.idle.app.media;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.edmodo.cropper.CropImageView;
import com.idle.android.R;
import com.idle.app.CustomProgressDialog;
import com.idle.util.UriUtil;

public class CustomCropActivity extends Activity {

    // Static final constants
    private static final int DEFAULT_ASPECT_RATIO_VALUES = 10;
    private static final int ROTATE_NINETY_DEGREES = 90;
    private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
    private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
    private static final int ON_TOUCH = 1;

    // Instance variables
    private int mAspectRatioX = DEFAULT_ASPECT_RATIO_VALUES;
    private int mAspectRatioY = DEFAULT_ASPECT_RATIO_VALUES;

    Bitmap croppedImage;
    
    protected int screenWidth;
	protected int screenHeight;
	protected Uri outputUri;
	protected Context context;
	
	CustomProgressDialog dialog;

    // Saves the state upon rotating the screen/restarting the activity
    @Override
    protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
        bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
    }

    // Restores the state upon rotating the screen/restarting the activity
    @Override
    protected void onRestoreInstanceState(Bundle bundle) {
        super.onRestoreInstanceState(bundle);
        mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
        mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
    }

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_crop);

        context = this;
        screenWidth = getWindow().getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindow().getWindowManager().getDefaultDisplay().getHeight();
        // Sets fonts for all
        /*Typeface mFont = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");
        ViewGroup root = (ViewGroup) findViewById(R.id.mylayout);
        setFont(root, mFont);*/

        // Initialize components of the app
        final CropImageView cropImageView = (CropImageView) findViewById(R.id.CropImageView);
        /*final SeekBar aspectRatioXSeek = (SeekBar) findViewById(R.id.aspectRatioXSeek);
        final SeekBar aspectRatioYSeek = (SeekBar) findViewById(R.id.aspectRatioYSeek);
        final ToggleButton fixedAspectRatioToggle = (ToggleButton) findViewById(R.id.fixedAspectRatioToggle);
        Spinner showGuidelinesSpin = (Spinner) findViewById(R.id.showGuidelinesSpin);*/
        
        // Sets sliders to be disabled until fixedAspectRatio is set
        /*aspectRatioXSeek.setEnabled(false);
        aspectRatioYSeek.setEnabled(false);*/

        // Set initial spinner value
        //showGuidelinesSpin.setSelection(ON_TOUCH);
        
        //Sets the rotate button
        /*final Button rotateButton = (Button) findViewById(R.id.Button_rotate);
        rotateButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cropImageView.rotateImage(ROTATE_NINETY_DEGREES);
            }
        });*/
        
        // Sets fixedAspectRatio
        /*fixedAspectRatioToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                cropImageView.setFixedAspectRatio(isChecked);
                if (isChecked) {
                    aspectRatioXSeek.setEnabled(true);
                    aspectRatioYSeek.setEnabled(true);
                }
                else {
                    aspectRatioXSeek.setEnabled(false);
                    aspectRatioYSeek.setEnabled(false);
                }
            }
        });*/

        //cropImageView.setImageResource(R.drawable.ic_launcher);
        // Sets initial aspect ratio to 10/10, for demonstration purposes
        cropImageView.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);
        cropImageView.setFixedAspectRatio(true);
        // Sets aspectRatioX
        /*final TextView aspectRatioX = (TextView) findViewById(R.id.aspectRatioX);

        aspectRatioXSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar aspectRatioXSeek, int progress, boolean fromUser) {
                try {
                    mAspectRatioX = progress;
                    cropImageView.setAspectRatio(progress, mAspectRatioY);
                    aspectRatioX.setText(" " + progress);
                } catch (IllegalArgumentException e) {
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // Sets aspectRatioY
        final TextView aspectRatioY = (TextView) findViewById(R.id.aspectRatioY);

        aspectRatioYSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar aspectRatioYSeek, int progress, boolean fromUser) {
                try {
                    mAspectRatioY = progress;
                    cropImageView.setAspectRatio(mAspectRatioX, progress);
                    aspectRatioY.setText(" " + progress);
                } catch (IllegalArgumentException e) {
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });*/


        // Sets up the Spinner
       /* showGuidelinesSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                cropImageView.setGuidelines(i);
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            }
        });*/

        /*final Button cropButton = (Button) findViewById(R.id.Button_crop);
        cropButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                croppedImage = cropImageView.getCroppedImage();
                ImageView croppedImageView = (ImageView) findViewById(R.id.croppedImageView);
                croppedImageView.setImageBitmap(croppedImage);
            }
        });*/
        
        final Button cropButton = (Button) findViewById(R.id.btnSave);
        cropButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
            	dialog = new CustomProgressDialog(context);
            	dialog.show();
            	new AsyncTask<Void, Void, Void>() {
					@Override
					protected void onPreExecute() {
						super.onPreExecute();
					}

					@Override
					protected Void doInBackground(Void... params) {
						croppedImage = cropImageView.getCroppedImage(path);
		                String path = UriUtil.getPathFromUri(getApplicationContext(), outputUri);
		                final File file = new File(path);
		                try {
		                    file.getParentFile().mkdirs();
		                    if (file.exists()) {
								file.delete();
							}
		                    //file.createNewFile();
		                    croppedImage.compress(CompressFormat.JPEG, 90, new FileOutputStream(file));
		                } catch (FileNotFoundException e) {
		                    e.printStackTrace();
		                }catch (Exception e) {
		                    e.printStackTrace();
		                }
						return null;
					}
					
					@Override
					protected void onPostExecute(Void result) {
						super.onPostExecute(result);
						dialog.dismiss();
						/*ImageView croppedImageView = (ImageView) findViewById(R.id.croppedImageView);
		                croppedImageView.setImageBitmap(croppedImage);*/
						setResult(RESULT_OK, getIntent().setData(outputUri));
		                /*ByteArrayOutputStream bs = new ByteArrayOutputStream();
		                croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, bs);
		                setResult(RESULT_OK, getIntent().putExtra("byteArray", bs.toByteArray()));*/
		                //setResult(RESULT_OK, getIntent().putExtra("data", croppedImage));
		                Log.i("CROP", "save");
		                finish();
					}
				}.execute();
            }
        });
        
        final Button cancleButton = (Button) findViewById(R.id.btnCancle);
        cancleButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
            	finish();
            }
        });

        Uri uri = getIntent().getData();
        if (uri != null) {
			new LoadImageUriTask(getApplicationContext(), cropImageView, uri).execute();
		}
        outputUri = getIntent().getParcelableExtra(MediaStore.EXTRA_OUTPUT);
    }

    private String path;
    private class LoadImageUriTask extends AsyncTask<Void, Void, Bitmap> {

    	private final int expectWidth = 1024;
        private final Uri mUri;
        private final CropImageView mCropImage;
        private final Context mContext;
        //private final String path;

        public LoadImageUriTask(Context context, CropImageView cropImage, Uri uri) {
        	mContext = context;
        	mCropImage = cropImage;
            mUri = uri;
            path = UriUtil.getPathFromUri(mContext, mUri);
			System.out.println("crop_pic_path_2:" + path);
        }

        protected Bitmap decode(BitmapFactory.Options options) {
            try {
                InputStream inputStream;
                if (mUri.getScheme().startsWith("http") || mUri.getScheme().startsWith("https")) {
                    inputStream = new URL(mUri.toString()).openStream();
                } else {
                    inputStream = mContext.getContentResolver().openInputStream(mUri);
                }
                return BitmapFactory.decodeStream(inputStream, null, options);
            } catch (OutOfMemoryError e) {
            	e.printStackTrace();
            	options.inSampleSize++;
            	return decode(options);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

		@Override
		protected Bitmap doInBackground(Void... params) {
			BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            decode(options);
            int scale = 1;
            while (checkSize(options.outWidth / scale > expectWidth, 
            		options.outHeight / scale > expectWidth, false)) {
                scale++;
            }

            /*scale--;
            if (scale < 1) {
                scale = 1;
            }*/
            options.inJustDecodeBounds = false;
            options.inSampleSize = scale;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inTempStorage = new byte[8 * 1024];
            Bitmap bitmap = decode(options);
            if (bitmap == null) {
            	return bitmap;
			}
			try {
				Bitmap tmp = scaledBitmap(bitmap, new ExifInterface(path));
				if (bitmap != tmp) {
					bitmap.recycle();
				}
	            bitmap = tmp;
			} catch (IOException e) {
				e.printStackTrace();
			}
            //System.out.println(bitmap.getWidth() +"w:h"+bitmap.getHeight());
			return bitmap;
		}

		private Bitmap scaledBitmap(Bitmap bitmap, ExifInterface exif) {
			if (exif == null) {
	            return scaledBitmap(bitmap);
	        }
			final Matrix matrix = new Matrix();
	        final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
	        int rotate = -1;

	        switch (orientation) {
	            case ExifInterface.ORIENTATION_ROTATE_270:
	                rotate = 270;
	                break;
	            case ExifInterface.ORIENTATION_ROTATE_180:
	                rotate = 180;
	                break;
	            case ExifInterface.ORIENTATION_ROTATE_90:
	                rotate = 90;
	                break;
	        }

	        if (rotate == -1) {
	        	return scaledBitmap(bitmap);
	        } else {
	            matrix.postRotate(rotate);
	            /*Bitmap scaledBmp = Bitmap.createScaledBitmap(bitmap, 
	            		screenWidth*bitmap.getWidth()/bitmap.getHeight(), 
	            		screenWidth, 
	            		true);
	            if (bitmap != scaledBmp) {
					bitmap.recycle();
					bitmap = null;
				}*/
	            Bitmap rotatedBmp = Bitmap.createBitmap(bitmap,
	            		0,
	            		0,
	            		bitmap.getWidth(),
	            		bitmap.getHeight(),
	            		matrix,
	            		true);
	            if (bitmap != rotatedBmp) {
	            	bitmap.recycle();
	            	bitmap = null;
				}
	            Bitmap scaledBmp = scaledBitmap(rotatedBmp);
	            if (rotatedBmp != scaledBmp) {
	            	rotatedBmp.recycle();
	            	rotatedBmp = null;
				}
	            return scaledBmp;
	        }
			
		}
		
		private Bitmap scaledBitmap(Bitmap bitmap) {
			if (bitmap.getWidth() >= screenWidth) {
				return bitmap;
			}
			return Bitmap.createScaledBitmap(bitmap, screenWidth, 
            		screenWidth*bitmap.getHeight()/bitmap.getWidth(), true);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result == null) {
				Toast.makeText(getApplicationContext(), 
						R.string.failed_to_load_image, Toast.LENGTH_SHORT).show();
			}else {
				mCropImage.setImageBitmap(result);
				mCropImage.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);
				mCropImage.setFixedAspectRatio(true);
				mBitmap = result;
				System.gc();
			}
		}

		private boolean checkSize(boolean widthBigger, boolean heightBigger, boolean isCropCenter) {
            if (isCropCenter) {
                return widthBigger && heightBigger;
            } else {
                return widthBigger || heightBigger;
            }
        }
    }
    /*
     * Sets the font on all TextViews in the ViewGroup. Searches recursively for
     * all inner ViewGroups as well. Just add a check for any other views you
     * want to set as well (EditText, etc.)
     */
    public void setFont(ViewGroup group, Typeface font) {
        int count = group.getChildCount();
        View v;
        for (int i = 0; i < count; i++) {
            v = group.getChildAt(i);
            if (v instanceof TextView || v instanceof EditText || v instanceof Button) {
                ((TextView) v).setTypeface(font);
            } else if (v instanceof ViewGroup)
                setFont((ViewGroup) v, font);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    Bitmap mBitmap;
    
	@Override
	protected void onDestroy() {
		if (mBitmap != null && !mBitmap.isRecycled()) {
			mBitmap.recycle();
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (dialog != null) {
			dialog.dismiss();
		}
		super.onPause();
	}
    
    

}
